package org.example.projecttwo.controller.content;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.example.projecttwo.common.Result;
import org.example.projecttwo.entity.Collection;
import org.example.projecttwo.entity.dto.content.request.CollectionDTO;
import org.example.projecttwo.entity.dto.content.request.CollectionSearchDTO;
import org.example.projecttwo.entity.dto.content.response.CollectionVO;
import org.example.projecttwo.service.ICollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/collections")
@Tag(name = "收藏管理", description = "收藏信息管理")
public class CollectionController {

    @Autowired
    private ICollectionService collectionService;

    @GetMapping("/{userId}/page")
    @Operation(summary = "分页查询用户收藏", description = "分页查询指定用户的收藏记录，支持按内容类型和标题搜索（标题搜索非必填） -- 收藏管理")
    public Result<IPage<CollectionVO>> pageUserCollections(
            @PathVariable @NotNull(message = "用户ID不能为空") Long userId,
            @RequestParam(required = false) Integer contentType,
            @RequestParam(required = false) String keyword,  // 非必填，用于关联内容的标题搜索
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {

        Page<CollectionVO> page = new Page<>(current, size);
        IPage<CollectionVO> result = collectionService.pageByUserWithSearch(
                userId, contentType, keyword, current, size);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取收藏详情", description = "根据收藏ID获取收藏详情 -- 收藏管理")
    public Result<CollectionVO> getCollectionDetail(@PathVariable Long id) {
        CollectionVO collection = collectionService.getDetailById(id);
        return Result.success(collection);
    }

    @PostMapping
    @Operation(summary = "添加收藏", description = "新增内容收藏 -- 收藏管理")
    public Result<Collection> addCollection(@Valid @RequestBody CollectionDTO dto) {
        // 检查用户是否已登录（实际项目中应通过拦截器统一处理）
        Collection collection = collectionService.createCollection(dto);
        return Result.success(collection);
    }

    @DeleteMapping("/cancel")
    @Operation(summary = "取消收藏", description = "根据内容信息取消收藏 -- 收藏管理")
    public Result<String> cancelCollection(@Valid @RequestBody CollectionDTO dto) {
        collectionService.removeCollection(dto);
        return Result.success("取消收藏成功");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除单个收藏", description = "根据收藏ID删除收藏 -- 收藏管理")
    public Result<String> deleteCollection(@PathVariable Long id) {
        collectionService.removeById(id);
        return Result.success("删除收藏成功");
    }

    @PostMapping("/batch-remove")
    @Operation(summary = "批量移除收藏", description = "批量移除用户收藏的内容 -- 收藏管理")
    public Result<String> batchRemove(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条收藏记录");
        }
        boolean success = collectionService.removeByIds(ids);
        if (success) {
            return Result.success("批量移除成功，共" + ids.size() + "条记录");
        } else {
            return Result.error("批量移除失败");
        }
    }

    @GetMapping("/check")
    @Operation(summary = "检查是否已收藏", description = "检查用户是否已收藏指定内容 -- 收藏管理")
    public Result<Boolean> checkCollection(
            @RequestParam Long userId,
            @RequestParam Integer contentType,
            @RequestParam Long contentId) {
        boolean isCollected = collectionService.checkCollection(userId, contentType, contentId);
        return Result.success(isCollected);
    }

    @GetMapping("/count")
    @Operation(summary = "获取内容收藏数", description = "统计指定内容的收藏数量 -- 收藏管理")
    public Result<Integer> getCollectionCount(
            @RequestParam Integer contentType,
            @RequestParam Long contentId) {
        int count = collectionService.countByContent(contentType, contentId);
        return Result.success(count);
    }

    @PostMapping("/user/article")
    @Operation(summary = "查询用户文章收藏", description = "查询用户收藏的所有文章，支持搜索 -- 收藏管理")
    public Result<IPage<CollectionVO>> getUserArticleCollections(
            @Valid @RequestBody CollectionSearchDTO searchDTO) {
        // 1表示文章类型
        IPage<CollectionVO> page = collectionService.pageByUserWithSearch(
                searchDTO.getUserId(),
                1,
                searchDTO.getKeyword(),
                searchDTO.getCurrent(),
                searchDTO.getSize());
        return Result.success(page);
    }

    @PostMapping("/user/news")
    @Operation(summary = "查询用户新闻收藏", description = "查询用户收藏的所有新闻，支持搜索 -- 收藏管理")
    public Result<IPage<CollectionVO>> getUserNewsCollections(
            @Valid @RequestBody CollectionSearchDTO searchDTO) {
        // 2表示新闻类型
        IPage<CollectionVO> page = collectionService.pageByUserWithSearch(
                searchDTO.getUserId(),
                2,
                searchDTO.getKeyword(),
                searchDTO.getCurrent(),
                searchDTO.getSize());
        return Result.success(page);
    }
}